import pymysql
from typing import Any, Dict
from pymysql.cursors import DictCursor
from retrying import retry
import urllib.parse
from sqlalchemy import create_engine

def R(code: int, success: bool, data: Any, msg: str) -> Dict[str, Any]:
    """
    格式化 API 返回的数据结构
    Args:
        msg: 返回的消息
        result: 返回的结果数据
    Returns:
        格式化后的字典数据
    """
    return {"code": code, "success": success, "data": data, "msg": msg}

@retry(wait_fixed=1000 * 10,  # 每次重试等待10秒钟
       stop_max_attempt_number=50,  # 最大重试次数10次
       retry_on_exception=lambda e: True,  # 任何异常都触发重试
       retry_on_result=lambda result: result is None  # 返回None时触发重试
)
def get_connect(user: str, pwd: str, host: str, port: int, db: str) -> pymysql.connections.Connection:
    try:
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=pwd,
            database=db,
            cursorclass=DictCursor
        )
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to MySQL: {e}")
        raise

def get_conn_engine(user, pwd, host, port, db):
    encoded_pwd = urllib.parse.quote(pwd)
    connectStr = f"mysql+pymysql://{user}:{encoded_pwd}@{host}:{port}/{db}?charset=utf8"
    engine = create_engine(connectStr)
    return engine

@retry(wait_fixed=1000 * 10,  # 每次重试等待10秒钟
       stop_max_attempt_number=50,  # 最大重试次数10次
       retry_on_exception=lambda e: True,  # 任何异常都触发重试
       retry_on_result=lambda result: result is None  # 返回None时触发重试
)
def get_conn_mp_alwaysup():
    # host = "43.153.52.217"
    host = "sh-cdb-h7flpxu4.sql.tencentcdb.com"
    port = 26300
    user = "root"
    pwd = "alwaysup@888"
    db = "alwaysup"
    return get_connect(user, pwd, host, port, db)

@retry(wait_fixed=1000 * 10,  # 每次重试等待10秒钟
       stop_max_attempt_number=50,  # 最大重试次数10次
       retry_on_exception=lambda e: True,  # 任何异常都触发重试
       retry_on_result=lambda result: result is None  # 返回None时触发重试
)
def get_data_mp_alwaysup(query, params=None):
    connection = None
    cursor = None
    try:
        # 获取数据库连接
        connection = get_conn_mp_alwaysup()
        with connection.cursor() as cursor:
            cursor.execute(query, params)  # 使用参数化查询，防止SQL注入
            data = cursor.fetchall()
        return data
    except Exception as e:
        # 记录错误日志
        print(f"Error executing query: {e}")
        return R(code=500, success=False, data=None, msg=str(e))
    finally:
        # 确保在结束时关闭游标和连接
        if cursor:
            try:
                cursor.close()
            except Exception as close_e:
                print(f"Error closing cursor: {close_e}")
        if connection:
            try:
                connection.close()
            except Exception as close_e:
                print(f"Error closing connection: {close_e}")


@retry(wait_fixed=1000 * 10,  # 每次重试等待10秒钟
       stop_max_attempt_number=50,  # 最大重试次数10次
       retry_on_exception=lambda e: True,  # 任何异常都触发重试
       retry_on_result=lambda result: result is None  # 返回None时触发重试
)
def get_Mpdb_engine(): 
    try:
        host = "sh-cdb-h7flpxu4.sql.tencentcdb.com"    
        port = 26300
        user = "root"
        pwd = "alwaysup@888"
        db = "alwaysup"
        engine = get_conn_engine(user, pwd, host, port, db) 
        engine.connect()
        print("腾讯mysql数据库连接成功！")
        return engine
    except Exception as e:
        print(f"Error mysql连接异常: {e}")